<?php

/**
 * 渠道控制器
 *
 * @author mengyuwang
 */

require_once 'CommonController.php';

class Admin_MemberController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_Member();
        $this->_memberManagerModel = new Application_Model_MemberManager();
       
        $this->view->title = "管理中心";
    }

    /**
     * 管理员的渠道列表动作
     * 
     * @return void
     */
    public function indexAdminAction()
    {   
        $this->view->suffix="admin";
        //获取当前页码
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }
        
        //设置URL模板
        $urls = array();
        $wheres = array();

        $name = trim($this->_request->get('name'));//
        if(!empty($name)) {
            $this->view->name = $name;
            $urls['name'] = $name;
            $wheres[] = "`name` LIKE '%" . addslashes($name) . "%'";
        }
        
        $code = trim($this->_request->get('code'));//
        if(!empty($code)) {
            $this->view->code = $code;
            $urls['code'] = $code;
            $wheres[] = "`code` LIKE '%" . addslashes($code) . "%'";
        }
        
        $status = $this->_request->isPost()?intval($this->_request->get('status')):-1;
        if($status!=-1) {
            $this->view->status = $status;
            $urls['status'] = $status;
            $wheres[] = "`status` = " . addslashes($status);
        } else {
        	  $this->view->status = -1;
        	  $urls['status'] = $status;
        }

        
        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
       
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';      
        $sql = "SELECT * 
            FROM `{$this->_model->getTableName()}` 
            {$where} 
            ORDER BY `addTime` desc
        ";
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();

        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        
    
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;

        

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        
        $this->view->rows = $dbPaginator->getRows();
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
    }
    
    public function indexManagerAction()
    {   
        $this->view->suffix="manager";
        //获取当前页码
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }
        
        //设置URL模板
        $urls = array();
        $wheres = array();
            $name = trim($this->_request->get('name'));//
        if(!empty($name)) {
            $this->view->name = $name;
            $urls['name'] = $name;
            $wheres[] = "`name` LIKE '%" . addslashes($name) . "%'";
        }
        
        $code = trim($this->_request->get('code'));//
        if(!empty($code)) {
            $this->view->code = $code;
            $urls['code'] = $code;
            $wheres[] = "`code` LIKE '%" . addslashes($code) . "%'";
        }
        
        $status = $this->_request->isPost()?intval($this->_request->get('status')):-1;
        if($status!=-1) {
            $this->view->status = $status;
            $urls['status'] = $status;
            $wheres[] = "`status` = " . addslashes($status);
        } else {
        	  $this->view->status = -1;
        	  $urls['status'] = $status;
        }
        

        $wheres[] = "t1.code = t2.memberCode";
        $currUserName = Application_Model_UserLogin::getInstance()->getLoginedUserName();
        $wheres[] = "managerUserName='{$currUserName}'";
        
        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
       
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';      
        $and = count($wheres) > 0 ? ' and ': '';

        $sql = "SELECT * 
            FROM `{$this->_model->getTableName()}`  as `t1`,`{$this->_memberManagerModel->getTableName()}` as `t2` 
            {$where} 
             ORDER BY t1.`id`
        ";

        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();

        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        
    
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;

        

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        
        $this->view->rows = $dbPaginator->getRows();
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
    }

    /**
     * 添加动作
     * 
     * @return void
     */
    public function insertAction()
    {
        if ($this->_request->isPost()) {
            $row = array();
            $filter = new Zend_Filter_StripTags();
            $row['code'] = $filter->filter(trim($this->_request->getPost('code')));
            $row['status'] = intval($this->_request->getPost('status'));  
            $row['fullName'] = $filter->filter(trim($this->_request->getPost('fullName')));
            $row['name'] = $filter->filter(trim($this->_request->getPost('name')));
            //$row['idNumber'] = $filter->filter(trim($this->_request->getPost('idNumber')));
            //$row['telephoneNumber'] = $filter->filter(trim($this->_request->getPost('telephoneNumber')));
            //$row['email'] = $filter->filter(trim($this->_request->getPost('email')));
            //$row['qq'] = $filter->filter(trim($this->_request->getPost('qq')));
            //$row['msn'] = $filter->filter(trim($this->_request->getPost('msn')));
            //$row['bankName'] = $filter->filter(trim($this->_request->getPost('bankName')));
            //$row['bankBranchName'] = $filter->filter(trim($this->_request->getPost('bankBranchName')));
            //$row['bankUserAccount'] = $filter->filter(trim($this->_request->getPost('bankUserAccount')));
            //$row['bankUserName'] = $filter->filter(trim($this->_request->getPost('bankUserName')));
           // $row['nameCode'] = $filter->filter(trim($this->_request->getPost('nameCode')));
            //$row['typeCode'] = $filter->filter(trim($this->_request->getPost('typeCode')));
            //$row['propertiesCode'] = $filter->filter(trim($this->_request->getPost('propertiesCode')));
            $row['url'] = $filter->filter(trim($this->_request->getPost('url')));
            $row['currency'] = $filter->filter(trim($this->_request->getPost('currency')));
            $row['creditValue'] = floatval($this->_request->getPost('creditValue')); 
            $row['creditLimitTime'] = $filter->filter(trim($this->_request->getPost('creditLimitTime')));
            $row['userName'] = $filter->filter(trim($this->_request->getPost('userName')));
            $row['password'] = md5($filter->filter(($this->_request->getPost('password'))));
            $row['notes'] = $filter->filter(trim($this->_request->getPost('notes')));
             $row['addTime'] = $row['lastModifyTime'] = date('Y-m-d H:i:s');
             //$row['ip'] = $_SERVER['REMOTE_ADDR'];
             
            if (strlen($row['code']) < 0) {
                echo $this->view->message('渠道编号长度不能小于6，请重新填写！') ;
                exit;
            }
            if (strlen($row['name']) < 1) {
                echo $this->view->message('渠道名称不能为空，请重新填写！') ;
                exit;
            }
            if (strlen($row['code']) > 50) {
                echo $this->view->message('渠道编号长度必须小于50个字符，请重新填写！') ;
                exit;
            }
            if (!(preg_match("/^[a-zA-Z0-9]{1,50}$/",$row['code']))) {
                echo $this->view->message('渠道编号填写英文字母、数字，请返回重新填写！') ;
                exit;
            }
            if ($this->_model->isExists($row['code'])) {
                echo $this->view->message('渠道编号已经存在，请重新填写！') ;
                exit; 
            }
            if (strlen($row['password']) < 5) {
                echo $this->view->message('密码长度不能小于5，请重新填写！') ;
                exit;
            }
            if (strlen($row['password']) > 50) {
                echo $this->view->message('密码长度必须小于50个字符，请重新填写！') ;
                exit;
            }
    
            $this->_model->insert($row);
            
            //插入关联的产品经理
             $row['managerUserName'] = $filter->filter(trim($this->_request->getPost('managerUserName')));
             $this->_memberManagerModel->updateRelationManager($row['code'],$row['managerUserName'],$this->_currentUserRow['userName']);
             
            echo $this->view->message('操作成功！', $this->view->projectUrl(array('action' => 'index-admin'))) ;
            exit;
        }
    }
    /**
     * 更新操作 - 管理员
     */
    public function updateAdminAction()
    {
        $this->view->suffix="admin";
        $this->update();
    }
    /**
     * 更新操作 - 渠道经理
     */
    public function updateManagerAction()
    {
        $this->view->suffix="manager";
        $this->update();
    }

    /**
     * 更新动作
     * 
     * @return void
     */
    public function update()
    {
        $id = intval($this->_request->get('id'));
        if (empty($id)) {
             throw new Exception('Invalid params!');
        }
        $this->view->row = $this->_model->fetchRow("`id` = {$id}"); 
        $this->view->managerUserName = $this->_model->getRelationManager($this->view->row['code']);
        if ($this->_request->isPost()) {
        $row = array();
            $filter = new Zend_Filter_StripTags();
            $row['code'] = $filter->filter(trim($this->_request->getPost('code')));
            $row['status'] = intval($this->_request->getPost('status'));  
            $row['name'] = $filter->filter(trim($this->_request->getPost('name')));
           
            //$row['url'] = $filter->filter(trim($this->_request->getPost('url')));
            //$row['currency'] = $filter->filter(trim($this->_request->getPost('currency')));
            //$row['creditValue'] = floatval($this->_request->getPost('creditValue')); 
            
            if($this->_request->getPost('password'))
            {
            	$row['password'] = md5($filter->filter(($this->_request->getPost('password'))));
            }
            $row['notes'] = $filter->filter(trim($this->_request->getPost('notes')));
            $row['lastModifyTime']  = date('Y-m-d H:i:s');

            if (strlen($row['code']) < 1) {
                echo $this->view->message('渠道编号长度不能小于1，请重新填写！') ;
                exit;
            }
            if (strlen($row['name']) < 1) {
                echo $this->view->message('渠道名称不能为空，请重新填写！') ;
                exit;
            }
            if (strlen($row['code']) > 50) {
                echo $this->view->message('渠道编号长度必须小于50个字符，请重新填写！') ;
                exit;
            }
            if (!(preg_match("/^[a-zA-Z0-9]{1,50}$/",$row['code']))) {
                echo $this->view->message('渠道编号填写英文字母、数字，请返回重新填写！') ;
                exit;
            }
            if ($this->_model->isExists($row['code'],$id)) {
                echo $this->view->message('渠道编号已经存在，请重新填写！') ;
                exit; 
            }
            if(isset($row['password']))
            {
                if (strlen($row['password']) < 5) {
                    echo $this->view->message('密码长度不能小于5，请重新填写！') ;
                    exit;
                }
                if (strlen($row['password']) > 50) {
                    echo $this->view->message('密码长度必须小于50个字符，请重新填写！') ;
                    exit;
                }
            }
            $this->_model->update($row, "`id` = {$id}");
            
            //更新关联渠道经理
            $row['managerUserName'] = $filter->filter(trim($this->_request->getPost('managerUserName')));
            if($this->view->managerUserName!=$row['managerUserName']) {
                $this->_memberManagerModel->updateRelationManager($row['code'],$row['managerUserName'],$this->_currentUserRow['userName']);
            }
          
            echo $this->view->message('操作成功！', $this->view->projectUrl(array('action' => 'index-'.$this->view->suffix))) ;
            exit;
        }
        
        $this->renderScript('member/update.php');
    }

    /**
     * 删除动作
     * 
     * @return void
     */
    public function deleteAction()
    {
        if ($this->_request->isPost()) {
            $ids= $this->_request->getPost('selectId');
            
            if (is_array($ids)) {
                foreach($ids as $id) {
                   $this->_model->delete($id);
                }
            }
        }
        $backUrl = urldecode($this->_request->get('backUrl'));
        redirect($backUrl);
    }
    
    /**
     * 检测member code是否存在
     * 
     * @return void
     */
    public function getMemberIsExistsByJsonAction()
    {
        $code = trim($this->_request->get('code'));
        $id = intval($this->_request->get('id'));
        $isExists = 1;
        if ($code != '') {
            $isExists = $this->_model->isExists($code,$id);
        }
        exit(Zend_Json::encode($isExists));
    }
}